import { useEffect, useRef, useState } from 'react'
import { ModalForm, ProFormCascader, ProFormText } from "@ant-design/pro-components"
import type { ProFormInstance } from '@ant-design/pro-components'
import { GetCascaderFnc, AddCategoryFnc, EditCategoryFnc } from '@/services/category'
import { message } from 'antd'
import { itemType } from './type'


const AddEdit = ({openType, isModalOpen, openBox, actionRef, catName, catID}: itemType) => {
  const formRef: any = useRef<ProFormInstance>()
  const [options, setOptions] = useState([]) // 级联选择器数据
  // 用于做比较的form
  const [formObj, setFormObj] = useState({})
  const [messageApi, contextHolder] = message.useMessage()
 
  // 添加分类盒子 级联选择器
  const init = async () => {
    if(openType === 'add') {
      const res = await GetCascaderFnc({type: 2})
      if(res.meta.status === 200) setOptions(res.data)
    } else if(openType === 'edit') {
      formRef.current.setFieldsValue({cat_name: catName})
      setFormObj({cat_name: catName})
    } else {
      return 
    }
  }
  useEffect(() => {init()}, [openType])

  // 公告消息
  const publicMsg = (msg: string) => {
    messageApi.success(msg, 1.5, () => {
      openBox(false)
      formRef.current.setFieldsValue({cat_name: ''})
      actionRef.current?.reload()
    })
  }

  const onFinish = async(value: {cat_name: string}) => {
    if(openType === 'add') {
      const res = await AddCategoryFnc({ cat_name: value.cat_name, cat_pid: 0, cat_level: 0 })
      if(res.meta.status === 201) publicMsg('添加成功') 
    } else {
      if(JSON.stringify(value) === JSON.stringify(formObj)) {
        openBox(false)
      } else {
        const res = await EditCategoryFnc(parseInt(catID), {cat_name: value.cat_name})
        if(res.meta.status === 200) publicMsg('修改成功') 
      }
    }
  }

  return (
    <>
    {contextHolder}
    <ModalForm
      title={openType === 'add' ? '添加分类' : '修改分类'}
      formRef={formRef}
      width={500}
      layout="horizontal"
      labelCol={{ span: 4 }}
      open={isModalOpen}
      onFinish={onFinish}
      modalProps={{ onCancel: () => openBox(false) }}
    >
      <ProFormText
        name="cat_name"
        label="分类名称"
        rules={[
          { required: true, message: '请输入分类名' },
          { min: 3, max: 10, message: '长度在3-10个字符' },
        ]}
      />
     
      {openType === 'add' 
      ? <ProFormCascader label="父级分类" name="cat_category" fieldProps={{options: options, fieldNames: {label: 'cat_name', value: 'cat_id', children: 'children'}}} />
       : ''
      }
    </ModalForm>
    </>
  )
}

export default AddEdit